<template>
  <div class="data-results">
    <div class="table-container" style="margin-top: 20px">
      <div class="table-header">
        <span class="table-title">项目信息对比</span>
      </div>
      <el-table :data="projectInfoData" stripe style="width: 100%">
        <el-table-column prop="infoName" label="对比项" width="180" />
        <el-table-column
          v-for="(id, index) in projectIds"
          :key="id"
          :prop="`project${index + 1}Value`"
          :label="`项目${index + 1}`"
        />
      </el-table>
    </div>
    <!-- 新增PCF对比分析部分 -->
    <div class="table-container" style="margin-top: 20px">
      <div class="table-header">
        <span class="table-title">外购产品PCF对比分析</span>
      </div>
      <!-- 修改表格，支持多列 -->
      <el-table :data="mergedOutMaterialTable" stripe style="width: 100%">
        <el-table-column prop="materialName" label="材料名称" />
        <el-table-column
          v-for="(id, index) in projectIds"
          :key="id"
          :prop="`project${index + 1}Supplier`"
          :label="`项目${index + 1}供应商`"
        />
      </el-table>
      <div ref="echarts2Ref" class="echarts"></div>
      <div class="description-container" style="margin-top: 20px">
        <p>{{ pcfComparisonText }}</p>
      </div>
    </div>
    <!-- 工艺PCF对比分析部分 -->
    <div class="table-container" style="margin-top: 20px">
      <div class="table-header">
        <span class="table-title">工艺PCF对比分析</span>
      </div>
      <div ref="echarts3Ref" class="echarts"></div>
      <div class="description-container" style="margin-top: 20px">
        <p>{{ processComparisonText }}</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="useProtable">
import { ref, onMounted, computed, watch, nextTick } from "vue";
import * as echarts from "echarts";
import { useEcharts } from "@/hooks/useEcharts";
import { Project } from "@/api/interface";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import axios from "axios";
const baseUrl = import.meta.env.VITE_BASE_URL;

const route = useRoute();
const echarts2Ref = ref<HTMLElement>(); // 新增PCF图表的引用
const echarts3Ref = ref<HTMLElement>(); // 新增工艺PCF图表的引用
/**实际使用的项目列表 */
const fetchedProjectList = ref<Partial<Project.ResProject>[]>([]);
const projectIds = computed(() => {
  const idsParam = (route.query.projectIds as string) || "";
  return idsParam.split(",").filter(id => id);
});
// 第一个表格数据，项目的所有外购数据PCF，外购来源厂，外购材料名
const PCFs_outMaterial = ref<any[]>([]);
const eachProcessPCF = ref<Array<{ projectId: string; eachProcessPCF: Array<{ name: string; value: number }> }>>([]);

// 挂载函数
onMounted(async () => {
  await fetchProjectInfoData();
  await initFormData(); // 先获取外购材料PCF
  console.log("PCFs_outMaterial:", PCFs_outMaterial.value);
  await nextTick(); // 确保数据加载完成
  initChart_PCFComparison();
  initChart_ProcessComparison();
});

const initFormData = async () => {
  PCFs_outMaterial.value = []; // 先清空
  const ids = projectIds.value;
  const promises = ids.map(async projectId => {
    try {
      const response = await axios.get(baseUrl + "/api/carbon/getFactoryName?projectId=" + projectId);
      if (response.data && response.data.code === 200) {
        return response.data.data;
      } else {
        const errorMsg = response.data.msg || "获取外购材料PCF失败";
        console.error(`项目${projectId}获取外购材料PCF错误:`, errorMsg);
        ElMessage.error(errorMsg);
        return null;
      }
    } catch (error) {
      console.error(`项目${projectId}获取外购材料PCF出错:`, error);
      ElMessage.error("获取外购材料PCF失败，可能是因为参数错误或网络问题");
      return null;
    }
  });
  // 等待所有请求完成
  const results = await Promise.all(promises);
  // 只保留有效数据
  PCFs_outMaterial.value = results.filter(item => item !== null);
  await fetchTotalPCF(); // 获取总碳足迹数据
  console.log("eachProcessPCF:", eachProcessPCF.value);
};

// 用于在表格上展示的数据
const mergedOutMaterialTable = computed(() => {
  // 获取所有唯一材料名
  const allNames = new Set<string>();
  PCFs_outMaterial.value.forEach(list => {
    list.forEach((item: any) => allNames.add(item.materialName));
  });

  // 构建表格数据
  return Array.from(allNames).map(materialName => {
    const row: any = { materialName };
    PCFs_outMaterial.value.forEach((list, projectIdx) => {
      const found = list.find((item: any) => item.materialName === materialName);
      row[`project${projectIdx + 1}Supplier`] = found?.supplierName || "-";
      row[`project${projectIdx + 1}PCF`] = found?.PCF ?? 0; // 这里加上PCF
    });
    return row;
  });
});

const fetchTotalPCF = async () => {
  const ids = projectIds.value;
  // 清空
  eachProcessPCF.value = [];

  const promises = ids.map(async (projectId) => {
    try {
      const response = await axios.post(`${baseUrl}/api/carbon/CalculateTotalPCF`, {
        projectId: Number(projectId)
      });

      if (response.data.code !== 200) {
        throw new Error(response.data.msg || "获取总碳足迹失败");
      }

      const data = response.data.data;
      // 只存储 eachProcessPCF，带上项目编号
      return {
        projectId,
        eachProcessPCF: Array.isArray(data.eachProcessPCF) ? data.eachProcessPCF : []
      };
    } catch (error) {
      console.error(`项目${projectId}获取总碳足迹失败:`, error);
      ElMessage.error(`项目${projectId}获取总碳足迹失败`);
      return {
        projectId,
        eachProcessPCF: []
      };
    }
  });

  // 等待所有请求完成
  const results = await Promise.all(promises);
  // 依次存入eachProcessPCF
  eachProcessPCF.value = results;
};

// 4. 修改高PCF材料计算逻辑
const highPCFMaterialByProject = computed(() => {
  return PCFs_outMaterial.value.map((list, idx) => {
    if (!Array.isArray(list) || list.length === 0) {
      return { projectName: `项目${idx + 1}`, highMaterial: { name: "未知", value: 0 } };
    }
    // 找到PCF最大的材料
    const maxItem = list.reduce((max, curr) => (curr.PCF > max.PCF ? curr : max), list[0]);
    return {
      projectName: `项目${idx + 1}`,
      highMaterial: {
        name: maxItem.materialName,
        value: maxItem.PCF
      }
    };
  });
});

// 5. 修改PCF对比文本
const pcfComparisonText = computed(() => {
  let text = "在各项目的PCF对比中，";

  highPCFMaterialByProject.value.forEach((item, index) => {
    text += `${item.projectName}的${item.highMaterial.name}PCF值为${item.highMaterial.value}kgCO₂eq`;
    if (index < highPCFMaterialByProject.value.length - 1) {
      text += "，";
    } else {
      text += "。";
    }
  });

  return text;
});

// 7. 修改PCF对比分析图表初始化函数
const initChart_PCFComparison = () => {
  if (!echarts2Ref.value) return;
  const myChart = echarts.init(echarts2Ref.value);
  const xAxisData = mergedOutMaterialTable.value.map(row => row.materialName);

  // 每个项目一条 series，data 为该项目下所有材料的 PCF
  const series = projectIds.value.map((id, projectIdx) => {
    const colors = ["#6B9DFE", "#4ECB73", "#FFA600", "#FF6B6B", "#A084E8", "#9AD0F5", "#F8D07A"];
    const color = colors[projectIdx % colors.length];
    const data = mergedOutMaterialTable.value.map(row => row[`project${projectIdx + 1}PCF`] ?? 0);

    return {
      name: `项目${projectIdx + 1}`,
      type: "bar",
      barWidth: `${80 / projectIds.value.length}%`,
      data,
      itemStyle: {
        color: color,
        borderRadius: [8, 8, 0, 0]
      },
      label: {
        show: true,
        position: "top",
        formatter: function (params: any) {
          return params.value.toFixed(2) + " kgCO2eq";
        }
      }
    };
  });

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: { type: "shadow" }
    },
    legend: {
      data: projectIds.value.map((id, idx) => `项目${idx + 1}`)
    },
    grid: {
      left: "3%",
      right: "10%",
      bottom: "15%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: xAxisData,
      axisLabel: {
        interval: 0,
        rotate: 45,
        fontSize: 12
      }
    },
    yAxis: {
      type: "value",
      name: "kgCO2eq",
      nameLocation: "middle",
      nameGap: 40
    },
    series: series
  };

  useEcharts(myChart, option);
};

// 项目信息对比数据（支持多项目）
const projectInfoData = ref<any[]>([]);

const fetchProjectInfoData = async () => {
  const ids = projectIds.value;
  // 并发获取所有项目的目标与范围数据
  const promises = ids.map(async (projectId) => {
    try {
      const response = await axios.get(baseUrl + "/api/carbon/getPurposeScopeDataById?projectId=" + projectId);
      if (response.data && response.data.code === 200) {
        return response.data.data;
      } else {
        return null;
      }
    } catch (error) {
      console.error(`项目${projectId}获取目标与范围数据失败:`, error);
      return null;
    }
  });
  const projectsData = (await Promise.all(promises)).filter(Boolean);

  // 定义要显示的信息项
  const infoItems = [
    { key: "productName", label: "产品名称" },
    { key: "systemBoundary", label: "系统边界" },
    { key: "functionalUnit", label: "功能单位" },
    { key: "dataPrinciple", label: "数据取舍原则" },
    { key: "dataQuality", label: "数据质量要求" },
    { key: "accountingBasis", label: "核算依据" },
    { key: "accountingMethod", label: "核算方法" }
  ];

  // 构建表格数据
  const tableData = infoItems.map(item => {
    const row: any = { infoName: item.label };
    projectsData.forEach((data, index) => {
      let value: string;
      if (item.key === "dataCollectionTime" && Array.isArray(data[item.key])) {
        value = data[item.key].length >= 2 ? `${data[item.key][0] || ""}~${data[item.key][1] || ""}` : "未设置";
      } else {
        value = data[item.key] || "未设置";
      }
      row[`project${index + 1}Value`] = value;
    });
    return row;
  });

  projectInfoData.value = tableData;
};

// 3. 找出每个项目中PCF值最高的工艺
const highProcessPCFByProject = computed(() => {
  return eachProcessPCF.value.map((project, idx) => {
    const processList = project.eachProcessPCF || [];
    if (!Array.isArray(processList) || processList.length === 0) {
      return { projectName: `项目${idx + 1}`, highProcess: { name: "未知", value: 0 } };
    }
    const highProcess = processList.reduce(
      (max, current) => (current.value > max.value ? current : max),
      processList[0]
    );
    return { projectName: `项目${idx + 1}`, highProcess };
  });
});

// 修改工艺PCF对比文本
const processComparisonText = computed(() => {
  let text = "在各项目的工艺PCF对比中，";

  highProcessPCFByProject.value.forEach((item, index) => {
    text += `${item.projectName}的${item.highProcess.name}PCF值为${item.highProcess.value.toFixed(2)}kgCO₂eq`;
    if (index < highProcessPCFByProject.value.length - 1) {
      text += "，";
    } else {
      text += "。";
    }
  });

  return text;
});

// 5. 修改工艺PCF对比分析图表初始化函数
const initChart_ProcessComparison = () => {
  if (!echarts3Ref.value) return;
  const myChart = echarts.init(echarts3Ref.value);

  // 1. 收集所有项目的所有工艺名称
  const allNamesSet = new Set<string>();
  (eachProcessPCF.value as Array<{ projectId: string; eachProcessPCF: Array<{ name: string; value: number }> }>).forEach(project =>
    project.eachProcessPCF.forEach((item: any) => allNamesSet.add(item.name))
  );
  const allNames = Array.from(allNamesSet);

  // 2. 构建 series，每个项目一条
  const series = (eachProcessPCF.value as Array<{ projectId: string; eachProcessPCF: Array<{ name: string; value: number }> }>).map((project, idx) => {
    // 按照 allNames 顺序，取出每个工艺的 value，没有则为0
    const data = allNames.map(name => {
      const found = project.eachProcessPCF.find((item: any) => item.name === name);
      return found ? Number(found.value) : 0;
    });
    const colors = ["#6B9DFE", "#4ECB73", "#FFA600", "#FF6B6B", "#A084E8", "#9AD0F5", "#F8D07A"];
    const color = colors[idx % colors.length];
    return {
      name: `项目${idx + 1}`,
      type: "bar",
      barWidth: `${80 / eachProcessPCF.value.length}%`,
      data,
      itemStyle: {
        color: color,
        borderRadius: [8, 8, 0, 0]
      },
      label: {
        show: true,
        position: "top",
        formatter: function (params: any) {
          return params.value.toFixed(2) + " kgCO2eq";
        }
      }
    };
  });

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: { type: "shadow" }
    },
    legend: {
      data: eachProcessPCF.value.map((_, idx) => `项目${idx + 1}`)
    },
    grid: {
      left: "3%",
      right: "10%",
      bottom: "15%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: allNames,
      axisLabel: {
        interval: 0,
        rotate: 45,
        fontSize: 12
      }
    },
    yAxis: {
      type: "value",
      name: "kgCO2eq",
      nameLocation: "middle",
      nameGap: 40
    },
    series: series
  };

  useEcharts(myChart, option);
};

// 监听 fetchedProjectList 的变化并更新图表
watch(
  () => fetchedProjectList.value,
  newVal => {
    if (newVal.length > 0) {
      initChart_PCFComparison();
      initChart_ProcessComparison();
    }
  },
  { immediate: true }
);
// 更新监听逻辑
watch(
  () => mergedOutMaterialTable.value,
  () => {
    initChart_PCFComparison();
  },
  { deep: true }
);
watch(
  () => eachProcessPCF.value,
  () => {
    initChart_ProcessComparison();
  },
  { deep: true }
);
</script>
<style>
.table-container {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}
.table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 12px;
  margin-bottom: 20px;
  border-bottom: 1px solid var(--el-border-color-light);
}
.table-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}
.echarts {
  width: 100%;
  height: 400px;
}
</style>
